# encoding: utf-8
class ContasController < ApplicationController
	include ApplicationUtils

	before_filter :load_conta, :only => [:show, :edit, :update, :destroy, :inativar]

	#
	#
	def index
		@contas = current_usuario.contas
	end
	
	#
	#
	def new
		@conta = Conta.new
	end
	
	#
	#
	def create
		@conta = Conta.new(params[:conta])
		@conta.usuario = current_usuario
		
		if (@conta.save)
			redirect_to contas_path, :notice => "Conta criada com sucesso!"
		else
			render :new
		end
	end
	
	#
	#
	def update
		if @conta.update_attributes(params[:conta])
			redirect_to contas_path, :notice => "Conta alterada com sucesso!"
		else
			render :edit
		end
	end

	#
	#
	def destroy
		if @conta.destroy
			flash[:notice] = "Conta excluída com sucesso!"
		end
		
		redirect_to contas_path
	end
	
	#
	#
	def inativar
		@conta.ativa = !@conta.ativa

		if @conta.save
			redirect_to contas_path,
				:notice => "Conta #{@conta.ativa ? 'ativada' : 'inativada'} com sucesso"
		else
			render :show
		end
	end
	
	private
	
	#
	#
	def load_conta
		@conta = Conta.find(params[:id])
		
		unless @conta.usuario == current_usuario
			redirect_to contas_path, :alert => "Operação inválida"
		end
	end
end
